package GoodsService

import (
	"context"
	"database/sql"
	"errors"
	"gdshop-font-api-go/app/response/GoodsResp"
	"gdshop-font-api-go/app/service/GoodsBaseService"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"strings"
)

func GetGoodsModelRaw(ctx context.Context, goodsId int) *GoodsResp.Details {
	goodsModel := GoodsResp.Details{}
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods").Where("id",
		goodsId).Struct(&goodsModel)
	if err != nil {
		if err != sql.ErrNoRows {
			g.Log().Async().Error("GetGoodsModelRaw " + err.Error())
			return nil
		}
	}
	if goodsModel.Id != uint(goodsId) {
		g.Log().Async().Error("GetGoodsModelRaw 找不到数据")
		return nil
	}
	return &goodsModel
}

func GetGoodsOptionsById(ctx context.Context, id int) *GoodsResp.GoodsOption {
	goodsOption := GoodsResp.GoodsOption{}
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_option").Where("id",
		id,
	).Order("display_sort DESC").Struct(&goodsOption)
	if err != nil {
		g.Log().Error("GetGoodsOptionsById " + err.Error())
		return nil
	}
	goodsOption.TitleArr = strings.Split(goodsOption.Title, ";")
	goodsOption.Title = strings.ReplaceAll(goodsOption.Title, ";", ",")
	return &goodsOption
}

func GetGoodsModel(ctx context.Context, goodsId int) (*GoodsResp.Details, error) {
	goodsModel := GetGoodsModelRaw(ctx, goodsId)
	if goodsModel == nil {
		return nil, errors.New("找不到goods数据")
	}
	GoodsBaseService.HandleDetails(ctx, goodsModel, true, 0)

	return goodsModel, nil
}

// 获取规格子项
func getGoodsSpecItems(ctx context.Context, goodsSpecId int) []*GoodsResp.GoodsSpecItem {
	goodsSpecItems := []*GoodsResp.GoodsSpecItem{}
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_spec_item").Where("spec_id=?",
		goodsSpecId,
	).Order("display_sort DESC,id DESC").Structs(&goodsSpecItems)
	if err != nil {
		return nil
	}
	return goodsSpecItems
}

// 获取规格选择项
func getGoodsSpecs(ctx context.Context, goodsId int) []*GoodsResp.GoodsSpec {
	goodsSpecs := []*GoodsResp.GoodsSpec{}
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_spec").Where("goods_id=?",
		goodsId,
	).Order("display_sort DESC,id DESC").Structs(&goodsSpecs)
	if err != nil {
		return goodsSpecs
	}

	for _, item := range goodsSpecs {
		item.Items = getGoodsSpecItems(ctx, item.Id)
	}

	return goodsSpecs
}

// 获取正文
// goodsId 商品ID
// typeString 类型 pc和mobile
func GetGoodsContent(ctx context.Context, goodsId int, typeString string) string {
	fieldName := ""
	if typeString == "pc" {
		fieldName = "goods_content"
	} else {
		fieldName = "goods_mobile_content"
	}
	con, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_extend").Where("goods_id=?",
		goodsId).Value(fieldName)

	if err != nil {
		return ""
	}

	return con.String()
}
